package com.chuangshu.chuangshuteam.util;

import cn.hutool.core.lang.UUID;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

@Component
public class File {
    // 1. 定义允许上传的文件MIME类型列表
    public static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList(
            "image/jpeg",  // .jpg, .jpeg
            "image/png",   // .png
            "image/gif",   // .gif
            "image/webp"   // .webp
    );

    public static final List<String> ALLOWED_DOCUMENT_TYPES = Arrays.asList(
            "application/pdf", // .pdf
            "application/msword", // .doc
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .docx
            "application/vnd.ms-excel", // .xls
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xlsx
            "text/plain" // .txt
    );

    @Autowired
    private MinioClient minioClient;
    @Value("${minio.image-bucket-name}")
    private  String imageBucketName;
    @Value("${minio.document-bucket-name}")
    private  String documentBucketName;
    @Value("${minio.common-bucket-name}")
    private  String commonBucketName;
    @Value("${minio.endpoint}")
    private  String endpoint;

    public  boolean isAllowedFileType(String fileType) {
        return ALLOWED_IMAGE_TYPES.contains(fileType) || ALLOWED_DOCUMENT_TYPES.contains(fileType);
    }
    public  String getFileType(String fileType) {

        if (ALLOWED_IMAGE_TYPES.contains(fileType)){
            return imageBucketName;
        }else if (ALLOWED_DOCUMENT_TYPES.contains(fileType)){
            return documentBucketName;
        }else {
            return "common";
        }

    }
    public  String uploadFile(byte[] fileBytes, String originalFilename, String contentType, String bucketName) throws Exception {
        // 1. 检查存储桶是否存在，如果不存在则创建
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            bucketName = commonBucketName;
        }

        // 2. 将 byte[] 转换为 InputStream
        InputStream inputStream = new ByteArrayInputStream(fileBytes);

        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String objectName = UUID.randomUUID() + fileExtension;

        // 3. 执行上传
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .stream(inputStream, fileBytes.length, -1) // 关键点: 使用字节数组的长度
                        .contentType(contentType) // 关键点: 手动指定contentType
                        .build()
        );

        // 关闭流
        inputStream.close();

        // 4. 拼接并返回文件的完整URL
        return endpoint + "/" + bucketName + "/" + objectName;
    }
    public boolean deleteByUrl(String url){
        if (url == null || url.isEmpty()) {
            return false;
        }
        try {
            // 从URL中解析bucketName和objectName
            String[] parts = url.replace(endpoint + "/", "").split("/", 2);
            if (parts.length != 2) {
                return false;
            }

            String bucketName = parts[0];
            String objectName = parts[1];

            // 执行删除操作
            minioClient.removeObject(
                    io.minio.RemoveObjectArgs.builder()
                            .bucket(bucketName)
                            .object(objectName)
                            .build()
            );

            return true;
        } catch (Exception e) {
            // 记录日志或处理异常
            e.printStackTrace();
            return false;
        }
    }
}
